import React, {useEffect, useState, useCallback} from 'react';
import Logo from '../components/Logo';
import Input from '../components/Input';
import ListItem from '../components/ListItem';
import Add from '../components/Add';
import Dialog from '../components/Dialog';
import styles from './index.module.css';

const Home = () => {
  const [siteList, setSiteList] = useState([]);
  const [visible, toggleVisible] = useState(false);
  useEffect(() => {
    // 从缓存中获取保存的链接
    const list = JSON.parse(localStorage.getItem('site_list') || '[{"name":"拉钩","link":"http://lagou.com"}]');
    setSiteList(list);
  }, []);
  useEffect(() => {
    localStorage.setItem('site_list', JSON.stringify(siteList));
  }, [siteList])
  const showDialog = useCallback(() => {
    toggleVisible(true);
  });
  const hideDialog = useCallback(() => {
    toggleVisible(false);
  });
  const pushSiteList = useCallback((item) => {
    setSiteList([...siteList, item]);
    hideDialog();
  });
  
  return (
    <main className={styles['app-container']}>
      <Logo />
      <Input />
      <div className={styles.flex}>
        {siteList.map((item, index) => <ListItem key={`${item.name}-${index}`} {...item} />)}
        <Add showDialog={showDialog}/>
      </div>
      {visible ? <Dialog pushSiteList={pushSiteList} cancel={hideDialog} /> : null}
    </main>
  )
}

export default Home;
